package com.geline.easyexcel.interfaces;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.geline.easyexcel.domain.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 基础数据库表操作基础实现类
 *
 * @author: mengxin
 * @date: 2024/1/25 10:18
 */
@Slf4j
public abstract class DBExcelCrudConsumer implements ExcelCrudConsumer {

    public abstract JdbcTemplate getJdbcTemplate();

    public abstract ExcelFileDao getExcelFileDao();

    @Transactional
    @Override
    public ExcelParseParam saveExcelFile(Map<String, List<ExcelError>> excelErrorMap, EasyExcelProperties properties, String filename, byte[] bytes) {
        ExcelFileEntity bean = new ExcelFileEntity();
        bean.setFilename(filename);
        bean.setBytes(bytes);
        bean.setErrorInfo(JSONUtil.toJsonStr(excelErrorMap));
        ExcelFileEntity entity = getExcelFileDao().save(bean);

        ExcelParseParam result = new ExcelParseParam();
        result.setFileId(entity.getId());
        return result;
    }

    @Transactional
    @Override
    public void deleteExcelFileByExpire(EasyExcelProperties properties) {
        String deleteSql = properties.getExpireDeleteSql();
        int update = getJdbcTemplate().update(deleteSql);
        log.info("deleteExcelFileByExpire success num : {}", update);
    }

    @Override
    public ExcelParseResult getExcelParseResult(String errorId) {
        ExcelFileEntity entity = getExcelFileDao().getById(errorId);
        String errorInfo = entity.getErrorInfo();
        ExcelParseResult result = new ExcelParseResult();
        result.setBytes(entity.getBytes());
        Map<String, List<ExcelError>> errorMap = JSONUtil.toBean(errorInfo, new TypeReference<Map<String, List<ExcelError>>>() {
        }, true);
        result.setExcelErrorMap(errorMap);
        return result;
    }
}
